package com.bjbn.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * T3能管平台WebAPI服务类
 *
 * @author bjbn
 */
@Service
public class Webapi4BmsService {

    @Autowired
    @Qualifier("httpWebClient")
    private WebClient httpWebClient;

    @Autowired
    private BmsTokenService bmsTokenService;

    @Value("${external.api.headers.x-hw-id.bms}")
    private String xHwId;

    @Value("${external.api.headers.x-hw-appkey.bms}")
    private String xHwAppkey;

    @Value("${external.bms.auth.code}")
    private String authCode;

    /**
     * 转发能管平台API请求（HTTP POST）
     *
     * @param endpoint    API端点
     * @param requestBody 请求体
     * @return 响应结果
     */
    public Mono<Map<String, Object>> forwardBmsApiRequest(String endpoint, Object requestBody) {
        return httpWebClient.post()
                .uri(endpoint)
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    // 记录错误日志
                    System.err.println("BMS API转发失败: " + endpoint + ", 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }

    /**
     * 转发能管平台API请求（HTTP GET）
     *
     * @param endpoint API端点
     * @return 响应结果
     */
    public Mono<Map<String, Object>> forwardBmsApiGetRequest(String endpoint) {
        String token = bmsTokenService.getCachedToken();
        if (token == null) {
            return Mono.error(new RuntimeException("未获取到有效token，请先调用获取token接口"));
        }

        return httpWebClient.get()
                .uri(endpoint)
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("token", token)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    // 记录错误日志
                    System.err.println("BMS API转发失败: " + endpoint + ", 错误: " + e.getMessage());
                    // 如果是401错误，清除token缓存
                    if (e.getMessage().contains("401")) {
                        bmsTokenService.clearToken();
                    }
                    return Mono.empty();
                });
    }

    /**
     * 获取能管平台Token
     *
     * @param timeout 超时时间（分钟）
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getBmsToken(int timeout) {
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("Code", authCode);
        requestBody.put("Timeout", timeout);

        return forwardBmsApiRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Token", requestBody)
                .doOnNext(response -> {
                    // 如果获取token成功，缓存token
                    if (response != null && (Boolean) response.get("success")) {
                        String token = (String) response.get("data");
                        bmsTokenService.cacheToken(token, timeout);
                    }
                });
    }

    /**
     * 获取维度列表
     *
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getCubeList() {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            // 如果没有有效token，先获取token
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Cube");
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Cube");
    }

    /**
     * 获取指定维度的树结构
     *
     * @param cubeCode 维度编号
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getDimensionTree(String cubeCode) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            // 如果没有有效token，先获取token
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Dimension/CubeCode?CubeCode=" + cubeCode);
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Dimension/CubeCode?CubeCode=" + cubeCode);
    }

    /**
     * 获取维度节点关联仪表信息
     *
     * @param cubeCode 维度编号
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getDimensionMeter(String cubeCode) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            // 如果没有有效token，先获取token
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/DimensionMeter/CubeCode?CubeCode=" + cubeCode);
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/DimensionMeter/CubeCode?CubeCode=" + cubeCode);
    }

    /**
     * 获取测量量类型
     *
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getMeasurandTypes() {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            // 如果没有有效token，先获取token
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Basic/Measurand");
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Basic/Measurand");
    }

    /**
     * 获取能源类型转换率
     *
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getEnergyRatios() {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            // 如果没有有效token，先获取token
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Basic/EnergyRatio");
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Basic/EnergyRatio");
    }

    /**
     * 获取维度节点指定小时/天/月/年时间段能耗数据
     *
     * @param requestBody 请求参数
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getDimensionEnergyConsumption(Object requestBody) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            String token = bmsTokenService.getCachedToken();
                            return httpWebClient.post()
                                    .uri("/CAN/BMS/EnergyManagementSystem/V1/api/EnergyConsumption/Dimension/MultFuncDetail")
                                    .header("X-HW-ID", xHwId)
                                    .header("X-HW-APPKEY", xHwAppkey)
                                    .header("token", token)
                                    .header("Content-Type", "application/json")
                                    .bodyValue(requestBody)
                                    .retrieve()
                                    .bodyToMono(Map.class)
                                    .cast(Map.class)
                                    .map(map -> (Map<String, Object>) map)
                                    .onErrorResume(e -> {
                                        System.err.println("BMS API转发失败: EnergyConsumption/Dimension/MultFuncDetail, 错误: " + e.getMessage());
                                        return Mono.empty();
                                    });
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        
        String token = bmsTokenService.getCachedToken();
        return httpWebClient.post()
                .uri("/CAN/BMS/EnergyManagementSystem/V1/api/EnergyConsumption/Dimension/MultFuncDetail")
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("token", token)
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    System.err.println("BMS API转发失败: EnergyConsumption/Dimension/MultFuncDetail, 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }

    /**
     * 获取日/月/年时段的定额数据
     *
     * @param requestBody 请求参数
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getNodeQuotaData(Object requestBody) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            String token = bmsTokenService.getCachedToken();
                            return httpWebClient.post()
                                    .uri("/CAN/BMS/EnergyManagementSystem/V1/api/QuotaDataManage/GetNodeQuotaData")
                                    .header("X-HW-ID", xHwId)
                                    .header("X-HW-APPKEY", xHwAppkey)
                                    .header("token", token)
                                    .header("Content-Type", "application/json")
                                    .bodyValue(requestBody)
                                    .retrieve()
                                    .bodyToMono(Map.class)
                                    .cast(Map.class)
                                    .map(map -> (Map<String, Object>) map)
                                    .onErrorResume(e -> {
                                        System.err.println("BMS API转发失败: QuotaDataManage/GetNodeQuotaData, 错误: " + e.getMessage());
                                        return Mono.empty();
                                    });
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        
        String token = bmsTokenService.getCachedToken();
        return httpWebClient.post()
                .uri("/CAN/BMS/EnergyManagementSystem/V1/api/QuotaDataManage/GetNodeQuotaData")
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("token", token)
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    System.err.println("BMS API转发失败: QuotaDataManage/GetNodeQuotaData, 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }

    /**
     * 获取所有设备ID及属性信息
     *
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getAllMeters() {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Basic/Meter");
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Basic/Meter");
    }

    /**
     * 获取单个设备下的所有测点数据
     *
     * @param meterId 设备ID
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getMeterPoints(String meterId) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Basic/Meter/" + meterId);
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/api/Basic/Meter/" + meterId);
    }

    /**
     * 获取多个AI遥测量实时值
     *
     * @param requestBody 请求参数
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getAIRange(Object requestBody) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            String token = bmsTokenService.getCachedToken();
                            return httpWebClient.post()
                                    .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/AIRange")
                                    .header("X-HW-ID", xHwId)
                                    .header("X-HW-APPKEY", xHwAppkey)
                                    .header("token", token)
                                    .header("Content-Type", "application/json")
                                    .bodyValue(requestBody)
                                    .retrieve()
                                    .bodyToMono(Map.class)
                                    .cast(Map.class)
                                    .map(map -> (Map<String, Object>) map)
                                    .onErrorResume(e -> {
                                        System.err.println("BMS API转发失败: IOServer/AIRange, 错误: " + e.getMessage());
                                        return Mono.empty();
                                    });
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        
        String token = bmsTokenService.getCachedToken();
        return httpWebClient.post()
                .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/AIRange")
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("token", token)
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    System.err.println("BMS API转发失败: IOServer/AIRange, 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }

    /**
     * 获取设备AI遥测量历史值
     *
     * @param requestBody 请求参数
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getMeterAIHistoryValue(Object requestBody) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            String token = bmsTokenService.getCachedToken();
                            return httpWebClient.post()
                                    .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/MeterAIHistoryValue")
                                    .header("X-HW-ID", xHwId)
                                    .header("X-HW-APPKEY", xHwAppkey)
                                    .header("token", token)
                                    .header("Content-Type", "application/json")
                                    .bodyValue(requestBody)
                                    .retrieve()
                                    .bodyToMono(Map.class)
                                    .cast(Map.class)
                                    .map(map -> (Map<String, Object>) map)
                                    .onErrorResume(e -> {
                                        System.err.println("BMS API转发失败: IOServer/MeterAIHistoryValue, 错误: " + e.getMessage());
                                        return Mono.empty();
                                    });
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        
        String token = bmsTokenService.getCachedToken();
        return httpWebClient.post()
                .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/MeterAIHistoryValue")
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("token", token)
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    System.err.println("BMS API转发失败: IOServer/MeterAIHistoryValue, 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }

    /**
     * 获取DI点信息
     *
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getDIPoints() {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/WebSiteDomain/api/Basic/DI");
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        return forwardBmsApiGetRequest("/CAN/BMS/EnergyManagementSystem/V1/WebSiteDomain/api/Basic/DI");
    }

    /**
     * 获取多个DI遥信量实时值
     *
     * @param requestBody 请求参数
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getDIRange(Object requestBody) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            String token = bmsTokenService.getCachedToken();
                            return httpWebClient.post()
                                    .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/DIRange")
                                    .header("X-HW-ID", xHwId)
                                    .header("X-HW-APPKEY", xHwAppkey)
                                    .header("token", token)
                                    .header("Content-Type", "application/json")
                                    .bodyValue(requestBody)
                                    .retrieve()
                                    .bodyToMono(Map.class)
                                    .cast(Map.class)
                                    .map(map -> (Map<String, Object>) map)
                                    .onErrorResume(e -> {
                                        System.err.println("BMS API转发失败: IOServer/DIRange, 错误: " + e.getMessage());
                                        return Mono.empty();
                                    });
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        
        String token = bmsTokenService.getCachedToken();
        return httpWebClient.post()
                .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/DIRange")
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("token", token)
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    System.err.println("BMS API转发失败: IOServer/DIRange, 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }

    /**
     * 获取仪表每小时/天/月/年时间段能耗数据
     *
     * @param requestBody 请求参数
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getMeterEnergyConsumption(Object requestBody) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            String token = bmsTokenService.getCachedToken();
                            return httpWebClient.post()
                                    .uri("/CAN/BMS/EnergyManagementSystem/V1/api/EnergyConsumption/Meter/MultFuncDetail")
                                    .header("X-HW-ID", xHwId)
                                    .header("X-HW-APPKEY", xHwAppkey)
                                    .header("token", token)
                                    .header("Content-Type", "application/json")
                                    .bodyValue(requestBody)
                                    .retrieve()
                                    .bodyToMono(Map.class)
                                    .cast(Map.class)
                                    .map(map -> (Map<String, Object>) map)
                                    .onErrorResume(e -> {
                                        System.err.println("BMS API转发失败: EnergyConsumption/Meter/MultFuncDetail, 错误: " + e.getMessage());
                                        return Mono.empty();
                                    });
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        
        String token = bmsTokenService.getCachedToken();
        return httpWebClient.post()
                .uri("/CAN/BMS/EnergyManagementSystem/V1/api/EnergyConsumption/Meter/MultFuncDetail")
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("token", token)
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    System.err.println("BMS API转发失败: EnergyConsumption/Meter/MultFuncDetail, 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }

    /**
     * 获取ACC量的实时表底值
     *
     * @param requestBody 请求参数
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getACCRangeWithInvalid(Object requestBody) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            String token = bmsTokenService.getCachedToken();
                            return httpWebClient.post()
                                    .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/ACCRangeWithInvalid")
                                    .header("X-HW-ID", xHwId)
                                    .header("X-HW-APPKEY", xHwAppkey)
                                    .header("token", token)
                                    .header("Content-Type", "application/json")
                                    .bodyValue(requestBody)
                                    .retrieve()
                                    .bodyToMono(Map.class)
                                    .cast(Map.class)
                                    .map(map -> (Map<String, Object>) map)
                                    .onErrorResume(e -> {
                                        System.err.println("BMS API转发失败: IOServer/ACCRangeWithInvalid, 错误: " + e.getMessage());
                                        return Mono.empty();
                                    });
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        
        String token = bmsTokenService.getCachedToken();
        return httpWebClient.post()
                .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/ACCRangeWithInvalid")
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("token", token)
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    System.err.println("BMS API转发失败: IOServer/ACCRangeWithInvalid, 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }

    /**
     * 获取ACC量的历史表底值
     *
     * @param requestBody 请求参数
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getAccHistoryValueByTimeType(Object requestBody) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            String token = bmsTokenService.getCachedToken();
                            return httpWebClient.post()
                                    .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/AccHistoryValueByTimeType")
                                    .header("X-HW-ID", xHwId)
                                    .header("X-HW-APPKEY", xHwAppkey)
                                    .header("token", token)
                                    .header("Content-Type", "application/json")
                                    .bodyValue(requestBody)
                                    .retrieve()
                                    .bodyToMono(Map.class)
                                    .cast(Map.class)
                                    .map(map -> (Map<String, Object>) map)
                                    .onErrorResume(e -> {
                                        System.err.println("BMS API转发失败: IOServer/AccHistoryValueByTimeType, 错误: " + e.getMessage());
                                        return Mono.empty();
                                    });
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        
        String token = bmsTokenService.getCachedToken();
        return httpWebClient.post()
                .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/AccHistoryValueByTimeType")
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("token", token)
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    System.err.println("BMS API转发失败: IOServer/AccHistoryValueByTimeType, 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }

    /**
     * 获取多个设备的通讯状态
     *
     * @param requestBody 请求参数
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getDevStatusRange(Object requestBody) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            String token = bmsTokenService.getCachedToken();
                            return httpWebClient.post()
                                    .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/DevStatusRange")
                                    .header("X-HW-ID", xHwId)
                                    .header("X-HW-APPKEY", xHwAppkey)
                                    .header("token", token)
                                    .header("Content-Type", "application/json")
                                    .bodyValue(requestBody)
                                    .retrieve()
                                    .bodyToMono(Map.class)
                                    .cast(Map.class)
                                    .map(map -> (Map<String, Object>) map)
                                    .onErrorResume(e -> {
                                        System.err.println("BMS API转发失败: IOServer/DevStatusRange, 错误: " + e.getMessage());
                                        return Mono.empty();
                                    });
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        
        String token = bmsTokenService.getCachedToken();
        return httpWebClient.post()
                .uri("/CAN/BMS/EnergyManagementSystem/V1/api/IOServer/DevStatusRange")
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("token", token)
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    System.err.println("BMS API转发失败: IOServer/DevStatusRange, 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }

    /**
     * 获取历史报警数据
     *
     * @param requestBody 请求参数
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getAlarmHistory(Object requestBody) {
        // 确保有有效的token
        if (!bmsTokenService.hasValidToken()) {
            return getBmsToken(10)
                    .flatMap(tokenResponse -> {
                        if (tokenResponse != null && (Boolean) tokenResponse.get("success")) {
                            String token = bmsTokenService.getCachedToken();
                            return httpWebClient.post()
                                    .uri("/CAN/BMS/EnergyManagementSystem/V1/api/Alarm/History")
                                    .header("X-HW-ID", xHwId)
                                    .header("X-HW-APPKEY", xHwAppkey)
                                    .header("token", token)
                                    .header("Content-Type", "application/json")
                                    .bodyValue(requestBody)
                                    .retrieve()
                                    .bodyToMono(Map.class)
                                    .cast(Map.class)
                                    .map(map -> (Map<String, Object>) map)
                                    .onErrorResume(e -> {
                                        System.err.println("BMS API转发失败: Alarm/History, 错误: " + e.getMessage());
                                        return Mono.empty();
                                    });
                        }
                        return Mono.just(tokenResponse);
                    });
        }
        
        String token = bmsTokenService.getCachedToken();
        return httpWebClient.post()
                .uri("/CAN/BMS/EnergyManagementSystem/V1/api/Alarm/History")
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("token", token)
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    System.err.println("BMS API转发失败: Alarm/History, 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }
}